const path=require('path')
const bcrypt=require('bcryptjs')
const db=require(path.join(__dirname,'../db/index'))
const jwt=require('jsonwebtoken')
const config=require(path.join(__dirname,'../config'))

exports.regUser=(req,res)=>{
    dbInsert_regUser(req.body,res)
}
exports.login=(req,res)=>{
    console.log(req.body)
    dbSelect_login(req.body,res)
}
exports.kala=(req,res)=>{
    // dbinsert(res)
    res.send('hello kala')
}
const dbSelect_login=(body,res)=>{
    const userinfo=body
    console.log(userinfo)
    const sqls='select * from ev_users where username=?'
    db.query(sqls,userinfo.username,(err,results)=>{
        if(err) return res.cc(err)
        if(results.length!==1) return res.cc('登录失败')
        // console.log('用户名存在')
        const compareResult=bcrypt.compareSync(userinfo.password,results[0].password)
        if(!compareResult){
            return res.cc('登录失败')
        }
        const user={...results[0],password:'',user_pic:''}  //剔除密码头像
        const tokenStr=jwt.sign(user,config.jwtSecretKey,{
            expiresIn:'10h'
        })
        return res.send({
            status:0,
            message:'登录成功',
            token:'Bearer '+ tokenStr
        })
    })
}
const dbInsert_regUser=(body,res)=>{
    const userinfo=body
    const sqls='select * from ev_users where username=?'
    db.query(sqls, userinfo.username, (err, results) => {
        if (err) return res.cc(err)
        if (results.length > 0) return res.cc('用户名被占用，请更换其他用户名！')
        // 调用 bcrypt.hashSync() 对密码进行加密
        userinfo.password = bcrypt.hashSync(userinfo.password, 10)
        const sqli='insert into ev_users set ?'
        db.query(sqli,{username:userinfo.username,password:userinfo.password},(err,results)=>{
            if(err) return res.cc(err)
            if(results.affectedRows!==1) return res.cc('注册失败')
            res.cc('注册成功',0)
        })
    })
    
}